import { createConnection } from 'typeorm';
import { config } from 'dotenv';
import { faker } from '@faker-js/faker/locale/zh_CN';

config();

// 定义更多的活动类型，按类别分组
const activityTypesByCategory = {
  骑行: ['休闲骑行', '山地骑行', '公路骑行', '夜骑', '亲子骑行', '环湖骑行', '长途骑行'],
  徒步: ['徒步旅行', '城市徒步', '山地徒步', '森林徒步', '海岸徒步', '峡谷徒步'],
  露营: ['野外露营', '沙滩露营', '森林露营', '湖边露营', '山顶露营'],
  摄影: ['风景摄影', '人像摄影', '街拍', '夜景摄影', '自然摄影'],
  登山: ['登山', '攀岩', '高山探险', '山脊徒步', '雪山攀登'],
  探索: ['城市探索', '古镇探索', '废墟探索', '地下探索', '历史建筑探索'],
  文化: ['文化体验', '传统工艺', '民俗活动', '文化节', '历史遗迹'],
  美食: ['美食之旅', '街头小吃', '农家美食', '特色餐厅', '美食节'],
  志愿: ['环保志愿', '社区服务', '教育志愿', '动物保护'],
  水上: ['皮划艇', '冲浪', '帆船', '游泳', '钓鱼']
};

// 将分类后的活动类型展平为一个数组
const activityTypes = Object.values(activityTypesByCategory).flat();

// 活动状态
const activityStatuses = ['DRAFT', 'RECRUITING', 'ONGOING', 'COMPLETED', 'CANCELLED'];

// 费用模式
const feeModes = ['FREE', 'PAID', 'DEPOSIT'];

// 难度级别
const difficultyLevels = ['EASY', 'MEDIUM', 'HARD'];

// 生成与活动类型相关的图片链接
function getActivityImageByType(activityType: string): string {
  // 活动类型映射到图片URL
  const typeImageMap: Record<string, string[]> = {
    // 骑行相关
    '休闲骑行': [
      'https://images.unsplash.com/photo-1517649763962-0c623066013b?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1541625602330-2277a4c46182?auto=format&q=80&w=1200&fit=crop'
    ],
    '山地骑行': [
      'https://images.unsplash.com/photo-1594076456781-b22a7d4729a8?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1544191696-102152079a3f?auto=format&q=80&w=1200&fit=crop'
    ],
    '公路骑行': [
      'https://images.unsplash.com/photo-1541625810516-44f1ce894bcd?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1517242810446-cc8951b2be40?auto=format&q=80&w=1200&fit=crop'
    ],
    '夜骑': [
      'https://images.unsplash.com/photo-1594143637509-f1e3b5fcada0?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1594818379496-da1e345b0ded?auto=format&q=80&w=1200&fit=crop'
    ],
    '亲子骑行': [
      'https://images.unsplash.com/photo-1551085254-e96b210db58a?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1502124011035-870cb339dff4?auto=format&q=80&w=1200&fit=crop'
    ],
    '环湖骑行': [
      'https://images.unsplash.com/photo-1455641374154-422f32e234cd?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1520101244246-293f77ffc39e?auto=format&q=80&w=1200&fit=crop'
    ],
    '长途骑行': [
      'https://images.unsplash.com/photo-1534787238916-9ba6764efd4f?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1506710507565-203b9f24669b?auto=format&q=80&w=1200&fit=crop'
    ],
    
    // 徒步相关
    '徒步旅行': [
      'https://images.unsplash.com/photo-1501555088652-021faa106b9b?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1552057426-9f23e61fa7b1?auto=format&q=80&w=1200&fit=crop'
    ],
    '城市徒步': [
      'https://images.unsplash.com/photo-1480714378408-67cf0d13bc1b?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1477959858617-67f85cf4f1df?auto=format&q=80&w=1200&fit=crop'
    ],
    '山地徒步': [
      'https://images.unsplash.com/photo-1551632811-561732d1e306?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1486911278844-a81c5267e227?auto=format&q=80&w=1200&fit=crop'
    ],
    '森林徒步': [
      'https://images.unsplash.com/photo-1448375240586-882707db888b?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1511497584788-876760111969?auto=format&q=80&w=1200&fit=crop'
    ],
    '海岸徒步': [
      'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1519046904884-53103b34b206?auto=format&q=80&w=1200&fit=crop'
    ],
    '峡谷徒步': [
      'https://images.unsplash.com/photo-1519681393784-d120267933ba?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1518457607834-6e8d80c183c5?auto=format&q=80&w=1200&fit=crop'
    ],
    
    // 露营相关
    '野外露营': [
      'https://images.unsplash.com/photo-1510312305653-8ed496efae75?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1537225228614-56cc3556d7ed?auto=format&q=80&w=1200&fit=crop'
    ],
    '沙滩露营': [
      'https://images.unsplash.com/photo-1523987355523-c7b5b0dd90a7?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1520824071669-892f70d8a23d?auto=format&q=80&w=1200&fit=crop'
    ],
    '森林露营': [
      'https://images.unsplash.com/photo-1533873984035-25970ab07461?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1478131143081-80f7f84ca84d?auto=format&q=80&w=1200&fit=crop'
    ],
    '湖边露营': [
      'https://images.unsplash.com/photo-1504851149312-7a075b496cc7?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1537565266759-34bbc16be345?auto=format&q=80&w=1200&fit=crop'
    ],
    '山顶露营': [
      'https://images.unsplash.com/photo-1526491109672-74740652b963?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1563299796-17596ed6b017?auto=format&q=80&w=1200&fit=crop'
    ],
    
    // 摄影相关
    '风景摄影': [
      'https://images.unsplash.com/photo-1554844453-7ea2a562a6c8?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&q=80&w=1200&fit=crop'
    ],
    '人像摄影': [
      'https://images.unsplash.com/photo-1542038784456-1ea8e935640e?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1511551203524-9a24350a5771?auto=format&q=80&w=1200&fit=crop'
    ],
    '街拍': [
      'https://images.unsplash.com/photo-1477959858617-67f85cf4f1df?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1514924013411-cbf25faa35bb?auto=format&q=80&w=1200&fit=crop'
    ],
    '夜景摄影': [
      'https://images.unsplash.com/photo-1519681393784-d120267933ba?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1515238152791-8216bfdf89a7?auto=format&q=80&w=1200&fit=crop'
    ],
    '自然摄影': [
      'https://images.unsplash.com/photo-1501854140801-50d01698950b?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1441974231531-c6227db76b6e?auto=format&q=80&w=1200&fit=crop'
    ],
    
    // 登山相关
    '登山': [
      'https://images.unsplash.com/photo-1551632811-561732d1e306?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1486911278844-a81c5267e227?auto=format&q=80&w=1200&fit=crop'
    ],
    '攀岩': [
      'https://images.unsplash.com/photo-1522163182402-834f871fd851?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1516592066400-86d98f3bc5bf?auto=format&q=80&w=1200&fit=crop'
    ],
    
    // 探索相关
    '城市探索': [
      'https://images.unsplash.com/photo-1480714378408-67cf0d13bc1b?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1477959858617-67f85cf4f1df?auto=format&q=80&w=1200&fit=crop'
    ],
    '古镇探索': [
      'https://images.unsplash.com/photo-1516834611397-8d633eaec5d0?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1530127796739-53cf66b0e41d?auto=format&q=80&w=1200&fit=crop'
    ],
    
    // 文化相关
    '文化体验': [
      'https://images.unsplash.com/photo-1551376347-075b0121a65b?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1577083552431-6e5fd01aa342?auto=format&q=80&w=1200&fit=crop'
    ],
    '传统工艺': [
      'https://images.unsplash.com/photo-1529066792305-5e4efa40fde9?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1528895977292-6d3a9c8dc2c8?auto=format&q=80&w=1200&fit=crop'
    ],
    
    // 美食相关
    '美食之旅': [
      'https://images.unsplash.com/photo-1504674900247-0877df9cc836?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1555939594-58d7cb561ad1?auto=format&q=80&w=1200&fit=crop'
    ],
    '街头小吃': [
      'https://images.unsplash.com/photo-1513639776629-7b61b0ac49cb?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1504674900247-0877df9cc836?auto=format&q=80&w=1200&fit=crop'
    ],
    
    // 志愿相关
    '环保志愿': [
      'https://images.unsplash.com/photo-1559027615-cd4628902d4a?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1560252829-804f1aedf1be?auto=format&q=80&w=1200&fit=crop'
    ],
    '社区服务': [
      'https://images.unsplash.com/photo-1593113598332-cd59a0c3a9a1?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1560252829-804f1aedf1be?auto=format&q=80&w=1200&fit=crop'
    ],
    
    // 水上活动
    '皮划艇': [
      'https://images.unsplash.com/photo-1544551763-92ab472cad5d?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1526761122248-c31c93f8b2b9?auto=format&q=80&w=1200&fit=crop'
    ],
    '冲浪': [
      'https://images.unsplash.com/photo-1502680390469-be75c86b636f?auto=format&q=80&w=1200&fit=crop',
      'https://images.unsplash.com/photo-1455729552865-3658a5d39692?auto=format&q=80&w=1200&fit=crop'
    ]
  };

  // 获取该活动类型的图片数组
  const images = typeImageMap[activityType] || [
    'https://images.unsplash.com/photo-1517649763962-0c623066013b?auto=format&q=80&w=1200&fit=crop',
    'https://images.unsplash.com/photo-1501555088652-021faa106b9b?auto=format&q=80&w=1200&fit=crop'
  ];

  // 随机选择一张图片
  return faker.helpers.arrayElement(images);
}

// 检查表结构
async function checkTableStructure(connection) {
  console.log('检查活动表结构...');
  try {
    const activityColumns = await connection.query('DESCRIBE activities');
    console.log('活动表列:', activityColumns.map(col => col.Field).join(', '));
    return activityColumns.map(col => col.Field);
  } catch (error) {
    console.error('检查表结构时出错:', error);
    return [];
  }
}

// 检查枚举值
async function checkEnumValues(connection) {
  try {
    const result = await connection.query(`
      SELECT COLUMN_TYPE 
      FROM INFORMATION_SCHEMA.COLUMNS 
      WHERE TABLE_NAME = 'activities' 
      AND COLUMN_NAME = 'feeMode'
    `);
    
    if (result && result.length > 0) {
      const columnType = result[0].COLUMN_TYPE;
      // 从 enum('FREE','PAID','AA','DEPOSIT') 格式中提取枚举值
      const enumMatch = columnType.match(/enum\((.+)\)/);
      if (enumMatch && enumMatch[1]) {
        const enumValues = enumMatch[1].split(',').map(val => 
          val.replace(/'/g, '').trim()
        );
        console.log('feeMode 枚举值:', enumValues);
        return enumValues;
      }
    }
    return null;
  } catch (error) {
    console.error('获取枚举值时出错:', error);
    return null;
  }
}

// 添加活动数据
async function addActivitiesWithImages() {
  console.log('开始添加带图片的活动数据...');
  
  const connection = await createConnection({
    name: 'testDataConnection',
    type: 'mysql',
    host: process.env.DB_HOST || 'localhost',
    port: Number(process.env.DB_PORT) || 3306,
    username: process.env.DB_USERNAME || 'root',
    password: process.env.DB_PASSWORD || '123456',
    database: process.env.DB_DATABASE || 'hdq-news',
    synchronize: false
  });

  try {
    // 检查表结构
    const columns = await checkTableStructure(connection);
    
    // 检查枚举值
    const feeModeEnumValues = await checkEnumValues(connection);
    const validFeeModes = feeModeEnumValues || feeModes;
    
    // 获取所有用户ID
    const userIds = await connection.query('SELECT id FROM users');
    if (!userIds || userIds.length === 0) {
      console.error('没有找到用户数据，请先添加用户');
      return;
    }
    const userIdList = userIds.map(user => user.id);
    console.log(`找到 ${userIdList.length} 个用户ID`);
    
    // 添加50个活动
    for (let i = 0; i < 50; i++) {
      try {
        // 随机选择一个用户作为创建者
        const creatorId = faker.helpers.arrayElement(userIdList);
        
        // 随机选择一个活动类型
        const activityType = faker.helpers.arrayElement(activityTypes);
        
        // 生成活动标题
        const title = `${activityType}: ${faker.location.city()}${faker.word.adjective()}之旅`;
        
        // 生成活动描述
        const description = faker.lorem.paragraphs(3);
        
        // 生成活动地点
        const location = faker.location.city();
        const address = faker.location.streetAddress(true);
        
        // 生成活动时间
        const startTime = faker.date.future();
        const endTime = new Date(startTime.getTime() + faker.number.int({ min: 3600000, max: 86400000 * 3 }));
        
        // 生成路线信息
        const routeDistance = faker.number.float({ min: 1, max: 50, fractionDigits: 1 });
        const routeDescription = faker.lorem.paragraph();
        
        // 生成参与人数
        const maxParticipants = faker.number.int({ min: 5, max: 100 });
        const minParticipants = faker.number.int({ min: 1, max: maxParticipants - 1 });
        const currentParticipants = faker.number.int({ min: 0, max: maxParticipants });
        
        // 生成费用信息
        const feeMode = faker.helpers.arrayElement(validFeeModes);
        const feeAmount = feeMode === 'FREE' ? 0 : faker.number.float({ min: 10, max: 500, fractionDigits: 2 });
        const depositAmount = feeMode === 'DEPOSIT' ? faker.number.float({ min: 50, max: 200, fractionDigits: 2 }) : 0;
        const feeDescription = feeMode === 'FREE' ? '免费活动' : `费用包含: ${faker.lorem.sentence()}`;
        
        // 生成难度级别
        const difficultyLevel = faker.helpers.arrayElement(difficultyLevels);
        
        // 生成要求和装备
        const requirements = faker.lorem.paragraph();
        const equipmentRequired = faker.lorem.paragraph();
        
        // 生成统计数据
        const viewCount = faker.number.int({ min: 0, max: 1000 });
        const favoriteCount = faker.number.int({ min: 0, max: 100 });
        const commentCount = faker.number.int({ min: 0, max: 50 });
        
        // 生成与活动类型相关的封面图
        const cover = getActivityImageByType(activityType);
        
        // 生成标签
        const tag = activityType;
        
        // 生成状态
        const status = faker.helpers.arrayElement(activityStatuses);
        
        // 构建插入SQL
        const insertSql = `
          INSERT INTO activities (
            title, description, location, address, startTime, endTime,
            routeDistance, routeDescription, maxParticipants, minParticipants,
            currentParticipants, feeMode, feeAmount, depositAmount, feeDescription,
            difficultyLevel, requirements, equipmentRequired,
            cover, tag, creatorId, status, createdAt, updatedAt
          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `;
        
        const values = [
          title, description, location, address, startTime, endTime,
          routeDistance, routeDescription, maxParticipants, minParticipants,
          currentParticipants, feeMode, feeAmount, depositAmount, feeDescription,
          difficultyLevel, requirements, equipmentRequired,
          cover, tag, creatorId, status, new Date(), new Date()
        ];
        
        await connection.query(insertSql, values);
        console.log(`已添加活动 ${i + 1}/50: ${title}`);
      } catch (error) {
        console.error(`添加活动 ${i + 1} 时出错:`, error);
      }
    }
    
    console.log('50条活动数据添加完成!');
  } catch (error) {
    console.error('添加活动数据时出错:', error);
  } finally {
    await connection.close();
    console.log('数据库连接已关闭');
  }
}

// 执行添加活动数据的函数
addActivitiesWithImages().catch(error => {
  console.error('脚本执行失败:', error);
  process.exit(1);
});


